local DB = require("common.DB")
local LuaMongo = _G.lua_mongo
local InnerDataManagerFW = require("innerdata.InnerDataManagerFW")
local InnerDataDefine = require("innerdata.Define")
local Util = require("common.Util")

dyMonsterData = dyMonsterData or {}

function init()
    LuaMongo.find(DB.db_dyMonster)
    while true do
        local nReader = {}
        if not LuaMongo.next(nReader) then
            break
        end

        local nData = {}
        Util.copyTable(nReader, nData)
        dyMonsterData[nData.monsterID] = nData 
    end
    local nSend2Ldata = {
        type = 1,
        data = dyMonsterData 
    }

    InnerDataManagerFW.Send2LInnerData(nil, InnerDataDefine.INNERDATA_TYPE_MONSTER, nSend2Ldata)
    --Util.printTable(dyMonsterData)
end

function update(updateData, fromClient)
    local nMonsterID = updateData.monsterID
    if not nMonsterID then
        return
    end

    if dyMonsterData[nMonsterID] then
        for k, v in pairs(updateData) do
            dyMonsterData[nMonsterID][k] = v
        end
    else
        dyMonsterData[nMonsterID] = updateData 
    end

    LuaMongo.update(DB.db_dyMonster, {monsterID = nMonsterID}, dyMonsterData[nMonsterID], true)
    
    if not fromClient then
        local nSend2Ldata = {
            type = 2,
            data = dyMonsterData[nMonsterID]
        }
        InnerDataManagerFW.Send2LInnerData(nil, InnerDataDefine.INNERDATA_TYPE_MONSTER, nSend2Ldata)
    end
end

function getDyMonsterData(monsterID)
    return dyMonsterData[monsterID]
end

function L2WProcess(human, type, oData)
    if oData.type == 1 then
        update(oData.data, true)
    end
end

InnerDataManagerFW.Register(InnerDataDefine.INNERDATA_TYPE_MONSTER, L2WProcess)
